<?php

function uninstall($app)

{
	try
	{
		$App=new app($app);

		if(!$App->exists())
		throw new \co2\Exception($app.'? No such app');
		
		$apps_manifest=main::getAppsManifest();
	
		$version=$apps_manifest->$app;
		
		require_once main::getSysVar('sources').'/'.$app.'-'.$version.'/uninstall.php';

		$uninstaller='co2_OS\apps\\'.$app.'\v'.preg_replace('/\./','\v',$version).'\uninstall';

		new $uninstaller;

		unset($apps_manifest->$app);

		if(!is_int(file_put_contents(main::getSysVar('apps-manifest'),json_encode($apps_manifest))))
		throw new \co2\Exception('failed to update apps manifest');	

		if(is_null($manifest=json_decode(file_get_contents(main::getSysVar('sources').'/'.$app.'-'.$version.'/manifest'))))
		throw new \co2\Exception('could not read app manifest');
		
		if(isset($manifest->create_sqlite_database) and file_exists($db=main::getSysVar('sqlite').'/'.$manifest->create_sqlite_database.'.'.main::getSysVar('sqlite-ext')) and !unlink($db))
		throw new \co2\Exception('could not remove app sqlite database');
		
		if(is_dir($public_bucket=main::getSysVar('bucket-apps').'/'.$app))
		new \co2\bash\rm($public_bucket,true);
		
		run('Trash')->dump($App->getBase());
	}
	catch(\co2\Exception $e)
	{
		throw new \co2\Exception($e->getMessage(),$e->getDebug(),$e->getLevel(),$e->getFile(),$e->getLine());
	}
}
